<template>
  <view class="form-item" v-if="item.mobileIsHidden" :class="{file:item.ui === '附件',required:required&&item.edit}">
    <view class="label">
      <text>{{ item.fieldtitle }}</text>
      <u-icon name="photo" v-if="item.ui === '图片附件' && item.edit" class="uploadImg" @click="uploadImg"></u-icon>
    </view>

    <template v-if="item.ui === '单行'">
      <view class="input">
        <input type="text" :value="value" :disabled="!item.edit" @input="input"
               :placeholder="item.placeholder||  (item.edit?'请输入':'')  "/>
      </view>
    </template>

    <template v-else-if="item.ui === '多行'">
      <view class="input">
        <textarea type="text" :value="value" :disabled="!item.edit" @input="input"
                  :placeholder="item.placeholder|| (item.edit?'请输入':'') "/>
      </view>
    </template>

    <template v-else-if="item.ui === '日期'">
      <view class="input">
        <view @click="openDatePicker" v-if="!value" class="placeholder">
          {{ item.placeholder || (item.edit ? '请选择' : '') }}
        </view>
        <view v-else="value" @click="openDatePicker" class="uni-input">{{ value }}</view>
        <u-picker show-time-tag @confirm="dateConfirm"
                  ref="datepicker"
                  :params="{
                            year: true,
                            month: true,
                            day: true,
                            hour: false,
                            minute: false,
                            second: false,
                        }"></u-picker>
      </view>
    </template>

    <template v-else-if="item.ui === '日期时间'">
      <view class="input">
        <view @click="openDatePicker" class="uni-input">{{ value }}</view>
        <view @click="openDatePicker" v-if="!value" class="placeholder">
          {{ item.placeholder || (item.edit ? '请选择' : '') }}
        </view>
        <u-picker show-time-tag @confirm="dateTimeConfirm" :params="{
                            year: true,
                            month: true,
                            day: true,
                            hour: true,
                            minute: true,
                            second: true,
                        }" v-model="showPicker"></u-picker>
      </view>
    </template>

    <template v-else-if="item.ui === '时间'">
      <view class="input">
        <view @click="openDatePicker" class="uni-input">{{ value }}</view>
        <view @click="openDatePicker" v-if="!value" class="placeholder">
          {{ item.placeholder || (item.edit ? '请选择' : '') }}
        </view>
        <u-picker
            show-time-tag
            @confirm="timeConfirm"
            :params="{
		                    year: false,
		                    month: false,
		                    day: false,
		                    hour: true,
		                    minute: true,
		                    second: false,
		                }"
            v-model="showPicker"></u-picker>
      </view>
    </template>

    <template v-else-if="item.ui==='单选'">
      <view class="input">
        <u-radio-group v-if="item.edit"
                       size="44rpx"
                       :value="value" @change="input">
          <u-radio
              v-for="(it, index) in options"
              :key="index"
              :name="it.value">
            {{ it.text }}
          </u-radio>
        </u-radio-group>
        <text v-else>{{ listText }}</text>
      </view>
    </template>

    <template v-else-if="item.ui==='复选'">
      <view class="input">
        <checkbox-group @change="input">
          <checkbox
              :disabled="!item.edit"
              v-for="(it, index) in options"
              :value="it.value"
              :checked="it.checked"
              style="margin-right: 30rpx;"
              :key="index">
            {{ it.text }}
          </checkbox>
        </checkbox-group>
      </view>
    </template>

    <template v-else-if="item.ui === 'html编辑器'">
      <view class="input">
        <u-parse :html="value"></u-parse>
      </view>
    </template>

    <template v-else-if="item.ui === '图片附件'">
      <view class="input img-box" v-if="imgList.length">
        <view class="img-item" v-for="(img,index) in imgList" :key="img.id">
          <u-icon v-if="item.edit" name="close" @click="deleteFile(img.id,'img')" class="closeIcon"></u-icon>
          <image @click="previewImg(index)" class="img-item" mode="aspectFill"
                 :src="img.url"></image>
        </view>

      </view>
    </template>

    <template v-else-if="item.ui === '附件'">
      <view class="input" style="display: flex;flex-wrap: wrap">
        <view class="file-item" v-for="file in fileList" :key="file.dowUrl">
          <view class="filename">{{ file.fileName }}</view>
          <view class="buttons">
            <u-button size="mini" shape="circle" type="primary" ripple @click="downloadFile(file)">预览
            </u-button>
            <u-button size="mini" shape="circle" type="error" ripple @click="deleteFile(file.id,'file')"
                      v-if="item.edit">
              删除
            </u-button>
          </view>
        </view>
        <view class="uploadFile" @click="uploadFile" v-if="item.edit">
          <u-icon name="plus"></u-icon>
        </view>

        <u-popup v-model="showSelectDialog" :border-radius="20" width="600rpx" mode="center">
          <view class="select-box">
            <view class="select-item" @click="androidUpload('album')">照片</view>
            <view class="select-item" @click="androidUpload('camera')">相机</view>
            <!-- #ifdef APP-PLUS -->
            <view class="select-item" v-if="!isIos" @click="androidUpload('file')">手机文件</view>
            <!-- #endif -->

          </view>
        </u-popup>
      </view>
    </template>

    <template v-else-if="item.ui === '列表'">

      <view class="input">
        <form-select ref="select" :items="options" :title="item.fieldtitle" :value="value"
                     style="width: 100%;height: 100%"
                     @change="input">
          <view @click="openSelect" style="width: 100%;height: 100%">
            <view v-if="value === ''"
                  class="placeholder">{{ item.placeholder || (item.edit ? '请选择' : '') }}
            </view>
            <view v-else class="uni-input">{{ listText }}</view>
          </view>
        </form-select>
      </view>
    </template>

    <template v-else-if="item.ui === '部门地址薄'">
      <view class="input">
        <view v-if="value === ''"
              @click="toDepartment"
              class="placeholder">{{ item.placeholder || (item.edit ? '请选择' : '') }}
        </view>
        <view v-else class="uni-input">{{ contactText }}</view>
      </view>
    </template>

    <template v-else-if="item.ui === '高级地址簿'">
      <!-- <view class="input">
          {{ listText }}
      </view> -->

      <view class="input">
        <view @click="toBuddyList" v-if="value === ''" class="placeholder">{{
            item.placeholder ||
            (item.edit ? '请选择' : '')
          }}
        </view>
        <view v-else @click="toBuddyList" class="uni-input">{{ contactText }}</view>
      </view>
    </template>

    <template v-else-if="item.ui === '并签'">
      <view class="input" v-if="!item.edit">
        <view v-for="data in addSignData" :key="data.id">
          <view>{{ data.fieldValue }}</view>
          <view style="text-align: right">
            <text style="padding-right: 10px;">{{ data.createUserName }}</text>
            <text>{{ data.createDate.split(" ")[0] }}</text>
          </view>
        </view>
      </view>
      <view class="input" v-else>
        <textarea type="text" :value="value" :disabled="!item.edit" @input="input"
                  :placeholder="item.placeholder|| (item.edit?'请输入':'') "/>
      </view>
    </template>

    <template v-else>
      <view class="input">
        {{ value }}
      </view>
    </template>
  </view>
</template>

<script>
import { Base64 } from '../../utils/base64.min.js'
import UButton from "../../uview-ui/components/u-button/u-button";
import { chooseFile, routeTo, arabia_To_SimplifiedChinese } from "../../utils/util";
import UIcon from "../../uview-ui/components/u-icon/u-icon";
import { baseURL, RESOURCE_DOWNLOAD } from "../../api/apiurl";
import { evaluate } from '../../libs/eval5/eval5.min.js'
import FormSelect from "../form-select";

export default {
  name: 'form-item',
  components: { FormSelect, UIcon, UButton },
  props: [ 'value', 'taskStatus', 'tableData', 'fieldModel', 'tableAc' ],
  inject: [ 'formId', 'sessionId', 'userNo', 'flowId', 'taskData' ],
  data() {
    return {
      imgList: [],
      fileList: [],
      showPicker: false,
      selectContactMap: null,
      showSelectDialog: false,
      isIos: false,
      watcherField: '',
      addSignData: '',
    };
  },
  computed: {
    required() {
      return this.item.null
    },
    item() {
      return this.fieldModel
    },
    options() {
      if (this.item.uivale === '') return ''
      if (this.item.ui === '高级地址簿') return ''
      if (this.item.ui === '部门地址薄') return ''
      try {
        return JSON.parse(this.item.uivale).map(e => {
          if (this.value) {
            e.checked = this.value.indexOf(e.value) !== -1
          } else {
            e.checked = false
          }
          return e
        })
      } catch (e) {
        console.error(this.item);
      }

    },
    listText() {
      if (this.options === '') return this.value
      return this.options.filter(e => e.value === this.value).map(e => e.text).join(' ')
    },
    contactText() {
      return this.value
    }
  },
  methods: {
    execScript() {
      if (this.item.appEditAfter) {
        this.$nextTick(function () {
          evaluate(this.item.appEditAfter, {
            context: this,
            setInterval,
            clearInterval,
            console
          });
        })
      }
    },
    dateTimeConfirm(e) {
      this.input(`${ e.year }-${ e.month }-${ e.day } ${ e.hour }:${ e.minute }:${ e.second }`)
    },
    openSelect() {
      if (!this.item.edit) return
      this.$refs.select.open()
    },
    androidUpload(type) {
      this.showSelectDialog = false
      let that = this;
      if (type === 'file') {
        chooseFile({
          success(res) {
            that.selectedHandler([ {
              path: 'file:///' + res
            } ], 'file')
          }
        })
      } else {
        uni.chooseImage({
          count: 9,
          sourceType: [ type ],
          sizeType: [ 'compressed' ],
          async success(res) {
            await that.selectedHandler(res.tempFiles.map((file, index) => {
              return {
                path: res.tempFilePaths[index]
              }
            }), type || 'img')
          }
        })
      }
    },
    async deleteFile(id, type) {
      uni.showLoading({
        title: '正在删除',
        mask: true
      })
      await this.api.deleteFile({ id: id });
      if (type === 'img') {
        await this.imgUrl()
      } else {
        await this.fileUrl()
      }
      uni.showToast({
        title: '删除成功',
      })
    },
    async selectedHandler(res, type) {
      let that = this;
      uni.showLoading({
        title: '上传中',
        mask: true
      })

      let results = []
      for (let i = 0; i < res.length; i++) {
        uni.showLoading({
          title: `正在上传${ i + 1 }/${ res.length }`
        })

        let [ err, data ] = await this.api.uploadFile({
          filePath: res[i].path,
          formData: {
            dicName: 'form',
            fieldId: that.item.fieldId,
            id: that.tableData.ID,
            formId: that.formId(),
            instanceId: that.tableData.INSTANCEID,
            flowId: that.flowId(),
            sessionId: that.sessionId()
          }
        })
        results.push(data);
      }
      uni.showToast({
        title: '上传成功'
      })
      if (type === 'img') {
        await that.imgUrl()
      } else {
        await that.fileUrl()
      }
      return results
    },
    uploadFile() {
      this.showSelectDialog = true
    },
    uploadImg(type) {
      let that = this;
      uni.chooseImage({
        count: 9,
        sizeType: [ 'compressed' ],
        async success(res) {
          await that.selectedHandler(res.tempFiles.map((file, index) => {
            return {
              path: res.tempFilePaths[index]
            }
          }), type || 'img')
        }
      })
    },
    /**
     * 设置修改天数
     * @param {Object} fieldName
     */
    setLeaveDay(leaveDay_field, startDate, startTime, endDate, endTime, fieldId) {
      let that = this;
      if (startDate != '' && startTime != '' && endDate != '' && endTime != "") {
        this.api.setLeaveDay({
          leaveDay_field: leaveDay_field,
          startDate: startDate,
          startTime: startTime,
          endDate: endDate,
          endTime: endTime,
          fieldId: fieldId
        }).then(data => {
          if (data.data.code == 0) {
            if (data.data.data > 0) {
              that.$emit('changeTableData', {
                key: leaveDay_field,
                value: data.data.data
              })
              // that.tableData[leaveDay_field] = data.data.data;
            } else {
              uni.showToast({
                icon: "none",
                title: "请正确选择请假日期",
                duration: 2000
              })
              that.$emit('changeTableData', {
                key: leaveDay_field,
                value: ''
              })
              // that.tableData[leaveDay_field] = "";
            }
          }
        })
      }
    },
    toDepartment() {
      if (this.item.edit) {
        let that = this;
        let params = JSON.parse(this.item.uivale)
        routeTo({
          link: 'department',
          params: {
            depIds: that.tableData[params.idField],
            ...params
          },
          events: {
            sendContactData(res) {
              // that.tableData[params.idField] = res.data.map(e => e.id).join(' ')
              that.$emit('changeTableData', {
                key: params.idField,
                value: res.data.map(e => e.id).join(' ')
              })
              that.input(res.data.map(e => e.name).join(' '))
              // that.tableData.isModify = true
              that.$emit('changeTableData', {
                key: 'isModify',
                value: true
              })
            }
          }
        })
      }
    },
    toBuddyList() {
      let that = this
      let params = JSON.parse(this.item.uivale)
      routeTo({
        link: 'buddyList',
        params: {
          userIds: that.tableData[params.idField],
          ...params
        },
        events: {
          sendContactData(res) {
            // that.tableData[params.idField] = res.data.map(e => e.id).join(' ')
            that.$emit('changeTableData', {
              key: params.idField,
              value: res.data.map(e => e.id).join(' ')
            })
            that.input(res.data.map(e => e.userName).join(' '))
            // that.tableData.isModify = true
            that.$emit('changeTableData', {
              key: 'isModify',
              value: true
            })
            if (that.fieldModel.appEditAfter != "") {
              //动态js
              // eval(that.fieldModel.appEditAfter)

              this.$nextTick(function () {
                evaluate(that.fieldModel.appEditAfter, {
                  context: that,
                  setInterval,
                  clearInterval,
                  console
                });
              })


            }
          }
        }
      })
    },
    dateConfirm(e) {
      this.input(`${ e.year }-${ e.month }-${ e.day }`)
    },
    timeConfirm(e) {
      this.input(`${ e.hour }:${ e.minute }`)
    },
    openDatePicker() {
      if (this.item.edit) {
        this.$refs.datepicker.open()
      }
    },
    downloadFile(file) {
      var office_type = [ 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf' ];
      var img_type = [ 'jpg', 'jpeg', 'bmp', 'gif', 'png' ];
      var acctype = file.fileName.substring(file.fileName.lastIndexOf(".") + 1, file.fileName.length);
      if (office_type.indexOf(acctype.toLocaleLowerCase()) != -1) {
        routeTo({
          link: 'file-preview',
          params: {
            id: file.id,
            fileName: file.fileName,
            fileType: "office_type"
          }
        })
      } else if (img_type.indexOf(acctype.toLocaleLowerCase()) != -1) {
        routeTo({
          link: 'file-preview',
          params: {
            id: file.id,
            fileName: file.fileName,
            fileType: "img_type"
          }
        })
      } else {
        uni.showToast({
          title: "不支持预览!",
          icon: "none"
        })
      }
    },
    previewImg(index) {

      uni.previewImage({
        urls: this.imgList.map(e => e.url),
        current: this.imgList[index].url
      })
    },
    async imgUrl() {
      this.api.getFileIds({
        sourceDataId: this.formId(),
        fieldId: this.item.fieldId,
        sessionId: this.sessionId()
      }).then(data => {
        this.imgList = data.data.map(e => {
          return {
            url: `${ baseURL }${ RESOURCE_DOWNLOAD }?userNo=${ this.userNo() }&sessionId=${ this.sessionId() }&id=${ e.id }&fileName=${ e.fileName }`,
            id: e.id
          }
        })
      })
    },
    async fileUrl() {
      this.api.getFileIds({
        sourceDataId: this.formId(),
        fieldId: this.item.fieldId,
        sessionId: this.sessionId()
      }).then(data => {
        this.fileList = data.data;
      })
    },
    select(e) {
      this.input(this.options[e.target.value].value)
      if (this.fieldModel.appEditAfter != "") {
        //动态js
        // eval(this.fieldModel.appEditAfter)

        this.$nextTick(function () {
          evaluate(this.fieldModel.appEditAfter, {
            context: this,
            setInterval,
            clearInterval,
            console
          });
        })
      }
      this.$emit('changeTableData', {
        key: 'isModify',
        value: true
      })
      // this.tableData.isModify = true
    },
    input(e) {
      let value;
      if (typeof e == 'string') {
        value = e
      } else if (e.target.value instanceof Array) {
        value = e.target.value.join(',')
      } else {
        value = e.target.value
      }
      this.$emit('input', value)
      if (this.fieldModel.appEditAfter != "") {
        //动态js
        this.$nextTick(function () {
          evaluate(this.fieldModel.appEditAfter, {
            context: this,
            setInterval,
            clearInterval,
            console
          });
        })
      }
      this.$emit('changeTableData', {
        key: 'isModify',
        value: true
      })
      // this.tableData.isModify = true
    },
    init() {
      if (this.item.ui === '图片附件') {
        this.imgUrl()
      } else if (this.item.ui === '附件') {
        this.fileUrl();
      }
      if (this.tableAc.split(',').indexOf('2') != -1 || (this.taskStatus != 0 && this.taskStatus != 1 && this.taskStatus != 2 && this.taskStatus != 5)) {
        this.item.edit = false;
      }
      if (this.item.ui === '大写金额') {
        this.watcherField = JSON.parse(this.item.uivale).bindField;
        this.$watch(
            () => this.tableData[this.watcherField],
            (newVal, oldVal) => this.input(arabia_To_SimplifiedChinese(newVal))
        )
      }
      if (this.item.ui === '并签') {
        let addSignData = this.tableData[this.item.fieldname + "_ADDSIGN_DATA"];
        if (addSignData != undefined) {
          this.addSignData = JSON.parse(Base64.decode(addSignData));
        } else {
          this.addSignData = [];
        }
      }
      this.isIos = uni.getSystemInfoSync().platform == "ios";
      if (this.item.appEditAfter) {
        this.$nextTick(function () {
          evaluate(this.item.appEditAfter, {
            context: this,
            setInterval,
            clearInterval,
            console
          });
        })
      }
    }
  },
  mounted() {
    this.init()
  }
}
</script>

<style lang="less">
.form-item {
  &.file {
    flex-direction: column;

    .label {
      display: flex;
      justify-content: space-between;
      width: 100% !important;
      text-align: left;
      border-right: 0;
      padding-right: 0;
    }
  }

  &.required {
    .input {
      border: 1px solid red;
    }
  }

  position: relative;
  //background: #FFFFFF;
  padding: 10rpx;
  //margin-bottom: 20rpx;
  display: flex;
  //border-radius: 10rpx;
  border-bottom: 1px solid #e6e6e6;

  .require {
    color: red;
    margin-right: 3rpx;
    display: flex;
    align-items: center;
    font-size: 40rpx;
  }

  .label {
    line-height: 40rpx;
    border-right: 1rpx solid #e6e6e6;
    font-weight: bold;
    text-align: right;
    width: 32%;
    display: flex;
    align-items: center;
    flex-shrink: 0;
    padding-right: 20rpx;
    justify-content: flex-end;
  }

  .input {
    flex: 1;
    height: auto;
    display: flex;
    align-items: center;
    border-radius: 5rpx;
    padding: 10rpx 10rpx;

    textarea, input, .uni-input {
      width: 100%;
    }

  }

  .img-box {
    display: flex;
    flex-wrap: wrap;


    .img-item {
      position: relative;
      height: 28vw;
      width: 28vw;
      margin-bottom: 20rpx;
      margin-right: 4vw;

      &:nth-child(3n) {
        margin-right: 0;
      }

    }

    .closeIcon {
      position: absolute;
      background: rgba(0, 0, 0, .2);
      padding: 10rpx;
      z-index: 10;
      border-radius: 100%;
      right: 0;
      color: #fff;
      top: 0;
      transform: translate(40%, -30%);
    }
  }

  .file-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 20rpx;
    width: 100%;

    &:last-child {
      margin-bottom: 0;
    }

    .u-btn {
      margin: 0;
    }

    .filename {
      width: 70%;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .buttons {
      display: flex;

      :first-child {
        margin-right: 20rpx;
      }
    }
  }

  .placeholder {
    color: #777;
    width: 100%;
  }

  .uploadImg {
    position: absolute;
    right: 0;
    font-size: 50rpx;
    color: #999;
    top: 50%;
    transform: translate(-50%, -50%);
  }

  .uploadFile {
    //margin-top: 40rpx;
    width: 100rpx;
    height: 100rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #EEE;

    .u-icon {
      font-size: 50rpx;
      color: #c1c1c1;
    }
  }

  .select-box {
    padding: 20rpx 40rpx;

    .select-item {
      font-size: 32rpx;
      line-height: 80rpx;
    }
  }
}
</style>
